<?php

namespace app\admin\controller\insurance;

use app\admin\model\InsuranceConfig;
use app\admin\service\TriggerService;
use app\common\constants\MenuConstant;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;
use app\common\controller\AdminController;
use app\Request;
use think\App;
use think\response\Json;

#[ControllerAnnotation(title: '配置')]
class Config extends AdminController
{
    protected array $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        self::$model = InsuranceConfig::class;
        $this->assign('p_titles', self::$model::$p_titles);
    }

    #[NodeAnnotation(title: '配置', auth: true)]
    public function index(Request $request): Json|string
    {
        $config = self::$model::find(1);
        // 初始化配置
        if (!$config) {
            $config = new self::$model();
            $settings = [
                'path_root' => '',
                'qe_rule_mode' => 0,
                'tax_point' => 0,
                'racharge_c_point' => 0,
                'excel_import_setting' => [],
                'ocr_type' => 0,
            ];
            $config['settings'] = $settings;
            $config->save();
        }
        
        if ($request->isAjax()) {
            $data = $request->post();
            // if (!empty($data['fields'])) {
            //     $fields = [];
            //     foreach ($data['fields'] as $key => $value) {
            //         $fields[] = [$value => $data['titles'][$key]];
            //     }
            // }
            // return json($fields);
            try {
                $config->settings = $data['settings'];
                $res = $config->save();
            } catch (\Exception $e) {
                return $this->error('配置失败');
            }
            if ($res) {
                // TriggerService::updateInsConfig();
                return $this->success('配置成功');
            } else {
                return $this->error('配置失败');
            }
        }
        $this->assign([
            'row' => $config,
        ]);
        return $this->fetch();
    }
}
